package com.heima.datasync.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.model.article.pojo.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vo.SearchArticleVo;
import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseOr;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author TheCai
 * @date 2021/6/8 20:10
 */
@Service
public class EsDataServiceImpl implements EsDataService {
  @Autowired ApArticleMapper apArticleMapper;

  @Autowired RestHighLevelClient restHighLevelClient;

  @Override
  public ResponseResult dataInit() {

    // 1.查询article 数据库中所有的文章数据
    List<ApArticle> allArticles = apArticleMapper.findAllArticles();
    if (allArticles == null || allArticles.size() == 0) {
      return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }

    // 2.将文章数据  封装成 vo对象  导入到索引库中
    // 2.1创建批量操作请求
    // TODO 批量导入的请求 不适合一次性导入特别多的文档,建议导入文章的数量1000-2000,可以分段导入

    // 例如8000文档   int page =1   int pagesize=2000  文档总页数(9);文档数量/pagesize
//    for (int page = 0; page < 9; page++) {
//      (page-1)*pageSize
//    }



    BulkRequest bulkRequest = new BulkRequest("app_info_article");
    allArticles.stream()
        .map( // 映射操作,将allArticle转化为articleVo
            allArticle -> {
              SearchArticleVo articleVo = new SearchArticleVo();
              BeanUtils.copyProperties(allArticle, articleVo);
              return articleVo;
            })
        .forEach( // 遍历
            vo -> {
              // 构建添加文档的请求
              IndexRequest indexRequest = new IndexRequest();
              indexRequest.id(vo.getId().toString()); // 设置文章id
              indexRequest.source(JSON.toJSONString(vo), XContentType.JSON); // 设置文档内容
              bulkRequest.add(indexRequest);
            });
// 2.2 使用客户端执行批量请求
    try {
      BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
      return ResponseResult.okResult(bulk.status());
    } catch (IOException e) {
      e.printStackTrace();
      return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "批量导入失败");
    }
  }
}
